package com.vrv.app.cyberspace.modules.sys.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.vrv.app.cyberspace.common.ddio.AllUserResult;
import com.vrv.app.cyberspace.common.ddio.ApiV2Service;
import com.vrv.app.cyberspace.common.ddio.DDIOUser;
import com.vrv.app.cyberspace.common.utils.JSONResult;
import com.vrv.app.cyberspace.common.utils.ToolUtil;
import com.vrv.app.cyberspace.common.web.RoleBean;
import com.vrv.app.cyberspace.modules.sys.entity.OrganizeTable;
import com.vrv.app.cyberspace.modules.sys.entity.UserTable;
import com.vrv.app.cyberspace.modules.sys.mapper.OrganizeTableMapper;
import com.vrv.app.cyberspace.modules.sys.mapper.UserTableMapper;
import com.vrv.app.cyberspace.modules.sys.service.IOrganizeTableService;
import com.vrv.app.cyberspace.modules.sys.service.IUserTableService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author sm
 * @since 2017-12-15
 */
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Service
@Transactional
public class UserTableServiceImpl extends ServiceImpl<UserTableMapper, UserTable> implements IUserTableService {
    Logger logger = LoggerFactory.getLogger(UserTableServiceImpl.class);

    @Autowired
    private UserTableMapper userTableMapper;
    @Autowired
    private ApiV2Service apiV2Service;

    @Autowired
    private IOrganizeTableService organizeTableService;

    @Autowired
    private OrganizeTableMapper organizeTableMapper;

    @Override
    public Integer insertUserTablesNoDupl(final List<UserTable> list) {
        Integer result = 0;
        List<UserTable> userTables = new ArrayList<>(list);
        List<UserTable> all = userTableMapper.selectList(new EntityWrapper<>());
        userTables.removeAll(all);
        if (userTables.size() > 0) {
            result = userTableMapper.insertBatch(ToolUtil.removeDuplInList(userTables));
        }
        return result;
    }

    @Override
    public JSONResult synchDDIOUser() {
        //同步组织
        logger.info("----同步组织开始----");
        organizeTableService.synchDDIOOrg();
        logger.info("----同步组织结束----");
        JSONResult jsonResult;
        try {
            Integer page = 1, totalPage = 0;
            logger.info("----同步人员开始----");
            do {
                //同步用户
                String apiUser = apiV2Service.getAllUser(page, 200);
                logger.info(apiUser);
                AllUserResult result = JSON.parseObject(apiUser, AllUserResult.class);
                if (totalPage == 0) totalPage = result.getTotalPage();//第一次获取到总页数后后面的循环就不在对他赋值
                List<UserTable> usertable = new ArrayList<>();
                UserTable user;
                OrganizeTable organizeTable;
                if (result.getCode() == 0) {
                    for (DDIOUser d : result.getUserSet()) {
                        user = d.createUserTable(apiV2Service.getServerUrl());
                        organizeTable = organizeTableMapper.selectById(user.getOrgID());
                        user.setOrgName(organizeTable != null ? organizeTable.getOrgName() : "");
                        usertable.add(user.clone());
                    }
                    userTableMapper.insertBatch(usertable);
                }
                page++;
            } while (page <= totalPage);
            logger.info("同步用户成功");
            jsonResult = JSONResult.renderSuccess();
        } catch (Exception e) {
            jsonResult = JSONResult.renderError();
            logger.info("同步用户失败");
            e.printStackTrace();
        }
        return jsonResult;
    }

    @Override
    public JSONResult distributeUserRole(RoleBean roleBean) {
        JSONResult jsonResult;
        try {
            List<String> orgIDs = JSONArray.parseArray(roleBean.getOrgIDs(), String.class);
            if (!CollectionUtils.isEmpty(orgIDs)) {
                organizeTableMapper.updateOrgRoleByIDS(orgIDs, roleBean.getRoleId());
                userTableMapper.updateUserRoleByOrgIDs(orgIDs, roleBean.getRoleId());
            }
            jsonResult = JSONResult.renderSuccess();
        } catch (Exception e) {
            jsonResult = JSONResult.renderError();
            e.printStackTrace();
        }
        return jsonResult;
    }
}
